package com.huangcy.gulimall.ware.listener;

import com.huangcy.common.to.mq.OrderTo;
import com.huangcy.common.to.mq.StockDetailTo;
import com.huangcy.common.to.mq.StockLockedTo;
import com.huangcy.common.utils.R;
import com.huangcy.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.huangcy.gulimall.ware.entity.WareOrderTaskEntity;
import com.huangcy.gulimall.ware.service.WareSkuService;
import com.huangcy.gulimall.ware.vo.OrderVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @program: gulimall
 * @description:
 * @author: huangcy
 * @create: 2022-09-15 15:21
 **/
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("订单死信队列发来消息，尝试解锁订单！");
        try {
            // 当前消息是否被第二次及以后（重新）派发过来的
//            Boolean redelivered = message.getMessageProperties().getRedelivered();
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 解锁失败 将消息重新放回队列，让别人消费
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("死信队列发来消息，尝试解锁库存！");
        try {
            wareSkuService.unlockStock(orderTo);
            // 手动删除消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);

        }

    }

}
